/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gestion;

import java.awt.Component;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import otros.Fecha;
import otros.Util;
import tablasSql.Articulos;
import tablasSql.RegStock;
import tablasSql.Stock;

/**
 *
 * @author FERRETERIA
 */
public class FStock extends javax.swing.JInternalFrame {

    public FStock() {
        initComponents();
        init();
    }
    
    private void init() {
        AnchoColumnas();
        tablaArticulo.setColumnSelectionAllowed(false);
        bBuscar.setFocusable(false);
        txtBusq.requestFocus(true);
        tablaArticulo.setAutoCreateRowSorter(true);
    }
    
    public FStock(String codigo) {
        initComponents();
        init();
        txtBusq.setText(codigo);
        Actualizar_Tabla();
        ActualizarCamposStock(codigo);
        txtStock.setEnabled(true);
        this.codigo = codigo;
    }
    
    public boolean hasArticulo() {
        if (tablaArticulo.getRowCount() > 0)
            return true;
        else
            return false;
    }

    private void AnchoColumnas() {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel)tablaArticulo.getColumnModel();
        TableColumn col = colModel.getColumn(2);        
        col.setPreferredWidth(70);
        col = colModel.getColumn(0);
        col.setPreferredWidth(50);
        col = colModel.getColumn(1);
        col.setPreferredWidth(300);
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaArticulo = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtBusq = new javax.swing.JTextField();
        bBuscar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtStock = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtFCreacion = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        txtFRegulacion = new javax.swing.JFormattedTextField();
        jLabel5 = new javax.swing.JLabel();
        txtFAntRegulacion = new javax.swing.JTextField();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Regulacion de Stock");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icono2.png"))); // NOI18N
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setMinimumSize(new java.awt.Dimension(250, 250));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 250));

        tablaArticulo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
            },
            new String [] {
                "Codigo", "Detalle", "Stock"
            }

        ));
        tablaArticulo.setColumnSelectionAllowed(true);
        tablaArticulo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaArticuloMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaArticulo);
        tablaArticulo.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jPanel1.setMinimumSize(new java.awt.Dimension(530, 55));
        jPanel1.setPreferredSize(new java.awt.Dimension(530, 55));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Criterio de busqueda:   ");
        jPanel1.add(jLabel1, new java.awt.GridBagConstraints());

        txtBusq.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtBusq.setToolTipText("");
        txtBusq.setMinimumSize(new java.awt.Dimension(250, 20));
        txtBusq.setPreferredSize(new java.awt.Dimension(250, 20));
        txtBusq.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtBusqMouseClicked(evt);
            }
        });
        txtBusq.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBusqKeyPressed(evt);
            }
        });
        jPanel1.add(txtBusq, new java.awt.GridBagConstraints());

        bBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        bBuscar.setToolTipText("Buscar");
        bBuscar.setPreferredSize(new java.awt.Dimension(55, 55));
        bBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bBuscarMouseClicked(evt);
            }
        });
        bBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                bBuscarKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
        jPanel1.add(bBuscar, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 0, 10);
        getContentPane().add(jPanel1, gridBagConstraints);

        jPanel2.setPreferredSize(new java.awt.Dimension(50, 50));
        jPanel2.setLayout(new java.awt.GridBagLayout());

        jLabel2.setText("Nuevo Stock:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        jPanel2.add(jLabel2, gridBagConstraints);

        txtStock.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtStock.setEnabled(false);
        txtStock.setPreferredSize(new java.awt.Dimension(76, 20));
        txtStock.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtStockMouseClicked(evt);
            }
        });
        txtStock.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtStockKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 2, 0);
        jPanel2.add(txtStock, gridBagConstraints);
        txtStock.getAccessibleContext().setAccessibleName("");

        jLabel3.setText("Fecha Creación:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        jPanel2.add(jLabel3, gridBagConstraints);

        txtFCreacion.setEditable(false);
        txtFCreacion.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFCreacion.setPreferredSize(new java.awt.Dimension(76, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 2, 0);
        jPanel2.add(txtFCreacion, gridBagConstraints);

        jLabel4.setText("Fecha de Regulación:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        jPanel2.add(jLabel4, gridBagConstraints);

        txtFRegulacion.setEditable(false);
        txtFRegulacion.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT))));
        txtFRegulacion.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFRegulacion.setPreferredSize(new java.awt.Dimension(76, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 2, 0);
        jPanel2.add(txtFRegulacion, gridBagConstraints);

        jLabel5.setText("Fecha de la anterior regulación:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel2.add(jLabel5, gridBagConstraints);

        txtFAntRegulacion.setEditable(false);
        txtFAntRegulacion.setPreferredSize(new java.awt.Dimension(76, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 2, 0);
        jPanel2.add(txtFAntRegulacion, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
        getContentPane().add(jPanel2, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bBuscarMouseClicked
        Actualizar_Tabla();
    }//GEN-LAST:event_bBuscarMouseClicked

    
    private void txtBusqKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusqKeyPressed
        if (evt.getKeyCode() == 10) { 
           Actualizar_Tabla();
           bBuscar.transferFocus();
        }
    }//GEN-LAST:event_txtBusqKeyPressed

    private void bBuscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bBuscarKeyPressed
        Actualizar_Tabla();
        if (evt.getKeyCode() == 10) 
            bBuscar.transferFocus();
    }//GEN-LAST:event_bBuscarKeyPressed

    String codigo = "";
    private void tablaArticuloMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaArticuloMouseClicked
        int fila = tablaArticulo.rowAtPoint(evt.getPoint());
        int columna = tablaArticulo.columnAtPoint(evt.getPoint());
        if ((fila > -1) && (columna > -1)) {
            if (tablaArticulo.getValueAt(fila,columna)!= null) {
                codigo = tablaArticulo.getValueAt(fila, 0).toString();
                ActualizarCamposStock(codigo);
                txtStock.setEnabled(true);
                txtStock.selectAll();
                txtStock.requestFocus();
            }
        }
    }//GEN-LAST:event_tablaArticuloMouseClicked

    private void txtStockKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtStockKeyPressed
        if (evt.getKeyCode() == 10) {
            if(JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, "¿Esta seguro de guardar?","Guardar", JOptionPane.OK_CANCEL_OPTION)) {
                String fecha = new Fecha().getFechaSQL();
                
                String fechaFor = null;
                String [] aFecha = null;
                if(!txtFRegulacion.getText().isEmpty()) {
                    aFecha = txtFRegulacion.getText().split("/");
                    fechaFor = aFecha[2] + "-" + aFecha[1] + "-" + aFecha[0];
                    
                    if (fecha.compareTo(fechaFor) == 0) {
                        if(txtFAntRegulacion.getText().compareTo("") == 0)
                            fechaFor = null;
                        else {
                            aFecha = txtFAntRegulacion.getText().split("/");
                            fechaFor = aFecha[2] + "-" + aFecha[1] + "-" + aFecha[0];
                        }
                    }
                }
                               
                String [] datos = {txtStock.getText(), fecha, fechaFor , ""+Articulos.getId(codigo)}; 
                Stock.guardar(datos, false);
                Actualizar_Tabla();
                //----------------------------------------------------memoria de modificacion de stock
                String [] datReg = {codigo, fecha + " " + new Fecha().getHora(), txtStock.getText()};
                RegStock.guardar(datReg);
                //--------------------------------------------------------------
                
                borrarCampos();
                txtStock.setEnabled(false);
                tablaArticulo.requestFocus();
            }
        }
    }//GEN-LAST:event_txtStockKeyPressed

    private void txtStockMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtStockMouseClicked
        txtStock.selectAll();
    }//GEN-LAST:event_txtStockMouseClicked

    private void txtBusqMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtBusqMouseClicked
        txtBusq.selectAll();
    }//GEN-LAST:event_txtBusqMouseClicked

    private void borrarCampos () {
        txtStock.setText("");
        txtFCreacion.setText("");
        txtFRegulacion.setText("");
        txtFAntRegulacion.setText("");
    }
 
    private void Actualizar_Tabla() {                    
        // se colocan los datos en la tabla
        String criterio = null;//cbBusq.getSelectedItem().toString();
        String valor = txtBusq.getText();
        //DefaultTableModel datos = Stock.getArticulosStock(criterio, valor);
        
        DefaultTableModel datos = null;
        try {
            Long.parseLong(valor);
            if (valor.length() > 6) {
                criterio = "codigoBarras1";
                datos = Stock.getArticulosStock(criterio, valor);
                if (datos == null)
                   criterio = "codigoBarras2";
            }
            else
                criterio = "codigo";
        } catch (Exception e) {
            criterio = "Detalle";
        }
        if (datos == null)
            datos = Articulos.getArticulos(criterio, valor, "");
        
        tablaArticulo.setModel(datos);  
        AnchoColumnas();
    }
    
    private void ActualizarCamposStock (String codigo) {
        try {
            ResultSet res = Stock.getStockArt(codigo);
            res.next();
            txtStock.setText(String.valueOf(res.getFloat("stockactual")));
            
            String [] date;
            String fecha = "";
            if (res.getString("FechaStockInicial") != null) {
                date = res.getString("FechaStockInicial").split("-"); 
                fecha = date [2].substring(0, 2) + "/" + date[1] + "/" + date [0];
            }
            txtFCreacion.setText(fecha);
            
            if (res.getString("FechaRegularizado") != null) {
                date = res.getString("FechaRegularizado").split("-");
                fecha = date [2].substring(0,2) + "/" + date[1] + "/" + date [0];
            }
            else
                fecha = "";
            txtFRegulacion.setText(fecha);
            
            if (res.getString("fechaanteriorreg") != null) {
                date = res.getString("fechaanteriorreg").split("-");
                fecha = date [2].substring(0,2) + "/" + date[1] + "/" + date [0];
            }
            else
                fecha = "";
            txtFAntRegulacion.setText(fecha);
        } catch (SQLException ex) {
            System.out.println ("ActualizazCamposStock: " + ex);
        }
    }
   
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bBuscar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaArticulo;
    private javax.swing.JTextField txtBusq;
    private javax.swing.JTextField txtFAntRegulacion;
    private javax.swing.JFormattedTextField txtFCreacion;
    private javax.swing.JFormattedTextField txtFRegulacion;
    public javax.swing.JTextField txtStock;
    // End of variables declaration//GEN-END:variables
}
